package com.project.lk.nurseapp.common.websocket;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;


import com.project.lk.nurseapp.R;
import com.project.lk.nurseapp.base.BaseApp;
import com.project.lk.nurseapp.base.UrlContants;
import com.project.lk.nurseapp.utils.JsonUtils;
import com.project.lk.nurseapp.utils.websocket.WsManager;
import com.project.lk.nurseapp.utils.websocket.WsStatusListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Response;
import okio.ByteString;

/**
 * 功能介绍：
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class WebSocketService extends Service {


    private String workStatus;// 当前工作状况，null表示正在处理，success表示处理成功，failure表示处理失败

    private String currAction; //标记当前请求头信息，在获取服务器端反馈的数据后，进行验证，以免出现反馈信息和当前请求不一致问题。比如现在发送第二个请求，但服务器端此时才响应第一个请求
    private WsManager wsManager;

    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        super.onCreate();
        Log.e("MLOG", "Service Create");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        SharedPreferences url = getSharedPreferences("url", Context.MODE_PRIVATE);
//        String urlId = url.getString("urlId", null);

        String wsUrl = intent.getStringExtra("wsUrl");
//        if (urlId==null){
//            urlId=new UserInfoUtils().getId();
//        }
//        String wsUrl = UrlContants.WEBSOCKET_URL + urlId;
        Log.e("MLOG",wsUrl);
        wsManager = new WsManager.Builder(BaseApp.getContext()).wsUrl(wsUrl).build();
        initWebSocket();
        return START_STICKY;
    }

    /**
     * 销毁
     */
    @Override
    public void onDestroy() {
        if (wsManager.isWsConnected()) {
            wsManager.stopConnect();
        }
        super.onDestroy();
        Log.e("MLOG", "Service Destroy");
    }

    private final IBinder mBinder = new WsBinder();
    NotificationManager mNM;
    private static int NOTIFY_ID = 1000;
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private void initWebSocket(){
        wsManager.startConnect();
        wsManager.setWsStatusListener(new WsStatusListener() {
            @Override
            public void onOpen(Response response) {
                super.onOpen(response);
                Log.e("MLOG","client request header:" + response.request().headers());
                Log.e("MLOG","client response header:" + response.headers());
                Log.e("MLOG","client response:" + response);
                Log.e("MLOG","client state");
                Log.e("MLOG","client onOpen");


            }
            @Override
            public void onMessage(String json) {//收消息的方法
                super.onMessage(json);
                //打印一些内容
                //sendNotification(BaseApp.getContext(),"点击查看消息","你有消息来了");
                Log.e("MLOG","client onMessage");
                Log.e("MLOG","message:" + json);
                MsgBean msgBean = (MsgBean) JsonUtils.getJsonUtils().toObject(MsgBean.class, json);
//                List<MsgBean> list=new ArrayList<MsgBean>();
//                list.add(msgBean);
//                EventBus.getDefault().post(new IMsgInfo(list));
            }

            @Override
            public void onMessage(ByteString bytes) {
                super.onMessage(bytes);
            }

            @Override
            public void onReconnect() {
                super.onReconnect();
            }

            @Override
            public void onClosing(int code, String reason) {
                super.onClosing(code, reason);
                Log.e("MLOG","client onClosing");
                Log.e("MLOG","code:" + code + " reason:" + reason);
            }

            @Override
            public void onClosed(int code, String reason) {
                super.onClosed(code, reason);
                //打印一些内容
                Log.e("MLOG","client onClosed");
                Log.e("MLOG","code:" + code + " reason:" + reason);
            }

            @Override
            public void onFailure(Throwable t, Response response) {
                super.onFailure(t, response);
                Log.e("MLOG","client onFailure");
                Log.e("MLOG","throwable:" + t);
                Log.e("MLOG","response:" + response);
            }
        });
    }
    private void restartApplication() {
        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    public void sendMsg(String msg){
        if(wsManager.isWsConnected())
            wsManager.sendMessage(msg);
    }
public class WsBinder extends Binder {
    public WebSocketService getService() {
        return WebSocketService.this;
    }


}
    /***
     * 发送通知
     * @param context
     * @param title
     * @param contentText
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static void sendNotification(Context context, String title, String contentText){
//        NotificationManager notifyMgr= (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
//        Intent resultIntent = new Intent(context, MessageActivity.class);//MainActivity  GetMesgActivity
//        resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//        PendingIntent pi = PendingIntent.getActivity(context, 0,resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//        Notification notification = new Notification.Builder(context)
//                .setSmallIcon(R.mipmap.xw_header)
//                .setTicker("点击查看消息")
//                .setContentTitle(title)
//                .setContentText(contentText)
//                .setContentIntent(pi)
//                .setDefaults(Notification.DEFAULT_ALL)//DEFAULT_VIBRATE
//                .build();
//        notification.flags |= Notification.FLAG_AUTO_CANCEL;
//        notifyMgr.notify(NOTIFY_ID, notification);
    }

}
